import React, {useState, useEffect} from 'react';
import {Panel} from '../../../components/Index';
import {Button, Select, Card, Form, Input, Table, Space, Avatar, Modal, message, List} from 'antd';
import {connect} from 'react-redux';
import ModalForm from './ModalForm';
import {PlusOutlined} from '@ant-design/icons';
import {get, post} from "../../../service";

function Product(props) {
    const [list, setList] = useState([]); //列表展示
    const [pagination, setPagination] = useState({}); //分页
    const [filter, setFilter] = useState({}); // 过滤条件

    useEffect(() => {
        onGetList();  // 获取用户列表
    }, []);

    const {modalForm} = props.productState;

    // 获取用户列表
    const onGetList = (params = {}) => {
        const query = {...filter, ...params}; // 合并已有的过滤条件
        get('/api/product/list', {params: query}).then(res => {
            console.log('list数据', res.records);
            setList(res.records);
            setPagination(res.pagination);
        });
    };


    // 搜索功能
    const onSearch = (values) => {
        setFilter(values);
        onGetList(values);
    };


    // 新增用户
    const OnAdd = () => {
        props.dispatch({
            type: 'showModalForm',
            data: {
                title: '新增',
                data: {},
                refreshList: onGetList
            }
        });
    };
    //查看详请
    const oView = (record) => {
        return () => {
            props.dispatch({
                type: 'showModalForm',
                data: {
                    title: '详请',
                    data: {...record, attrs: JSON.parse(record.attrs)},
                }
            })
        }
    }
    // 删除用户
    const onRemove = (record) => {
        return () => {
            Modal.confirm({
                title: '删除',
                content: '确定要删除吗？',
                onOk: async () => {
                    try {
                        await post('/api/product/delete', {id: record.id});
                        message.success("删除成功");
                        onGetList();
                    } catch (error) {
                        message.error("删除失败");
                    }
                }
            });
        };
    };
    // 编辑用户
    const onEdit = (record) => {
        return () => {
            props.dispatch({
                type: 'showModalForm',
                data: {
                    title: '编辑',
                    data: {...record, attrs: JSON.parse(record.attrs)},
                    refreshList: onGetList
                }
            })
        }
    }
    return (
        <Panel title="商品管理">
            <Card className='m-filter'>
                <Form layout="inline" onFinish={onSearch}>
                    <Form.Item label="商品名称" name="name">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="商品类型" name="type">
                        <Select style={{width: 200}} allowClear>
                            <Select.Option value="0">图书</Select.Option>
                            <Select.Option value="1">服装</Select.Option>
                            <Select.Option value="2">电器</Select.Option>
                            <Select.Option value="3">家具</Select.Option>
                            <Select.Option value='4'>数码</Select.Option>
                            <Select.Option value='5'>食品</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
            </Card>
            <Card>
                <div className="m-operate">
                    <Button type="primary" icon={<PlusOutlined/>} onClick={OnAdd}>新增</Button>
                </div>
                <List dataSource={list} pagination={{
                    ...pagination,
                    showTotal: (total) => `共${total}条数据`,
                    onChange: (current) => {
                        onGetList({...filter, current})
                    }
                }}
                      renderItem={(item) => (
                          <List.Item actions={[
                              <a onClick={oView(item)}>查看</a>,
                              <a onClick={onEdit(item)}>编辑</a>,
                              <a onClick={onRemove(item)}>删除</a>
                          ]}>
                              <List.Item.Meta avatar={<Avatar src={item.mainPic}/>} title={item.name}
                                              description={['图书', '服装', '电器', '家具', '数码', '食品'][item.type]}/>
                              <Space>
                                  {item.price ? <span style={{color: 'red'}}>
                                      {`${item.price}`}
                                  </span> : null}
                                  <span>{JSON.parse(item.attrs).map(attr => attr.key + ":" + attr.value) + ";"}</span>
                              </Space>
                          </List.Item>
                      )}
                ></List>
            </Card>
            {modalForm && <ModalForm {...modalForm} {...props} />}
        </Panel>
    );
}

const mapStateToProps = (store) => ({productState: store.product});
const mapDispatchToProps = (dispatch) => ({
    dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(Product);
